package cn.kgc.config;

import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author YC
 */
@Configuration
public class ZookeeperConnector {

    /**
     * zookeeper地址端口号
     */
    private static final String ZK_ADDRESS = "192.168.8.106:2181";
    /**
     * 会话超时时间
     */
    private static final int SESSION_TIMEOUT = 5000;
    /**
     * Zookeeper连接
     */
    public static ZooKeeper zooKeeper;

    /**
     * 获取Zookeeper连接
     * 注解@PostConstruct：在构造方法执行之后执行
     */
    @PostConstruct
    public void init() {
        try {
            zooKeeper = new ZooKeeper(ZK_ADDRESS, SESSION_TIMEOUT, null);
        } catch (Exception e) {
            throw new RuntimeException("Zookeeper连接失败");
        }
    }

    /**
     * 关闭连接，自动
     * 注解@PreDestroy：在Bean销毁之前执行
     */
    @PreDestroy
    public static void close() {
        try {
            if (zooKeeper != null) {
                zooKeeper.close();
            }
        } catch (Exception e) {
            throw new RuntimeException("Zookeeper关闭失败");
        }
    }

}
